<template>
  <el-card class="chart-card" :body-style="{ padding: '20px' }">
    <div slot="header" class="chart-header">
      <span class="chart-title">{{ title }}</span>
      <div class="chart-actions">
        <slot name="actions"></slot>
      </div>
    </div>
    <div class="chart-container" :style="{ height: height + 'px' }">
      <div ref="chart" :style="{ width: '100%', height: '100%' }"></div>
    </div>
  </el-card>
</template>

<script>
// import * as echarts from 'echarts'
let echarts = null

// 动态导入 echarts，如果失败则使用模拟对象
try {
  echarts = require('echarts')
} catch (error) {
  console.warn('ECharts 未安装，使用模拟对象')
  echarts = {
    init: () => ({
      setOption: () => {},
      dispose: () => {},
      resize: () => {}
    })
  }
}

export default {
  name: 'ChartCard',
  props: {
    title: {
      type: String,
      required: true
    },
    height: {
      type: Number,
      default: 300
    },
    options: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    options: {
      handler(newOptions) {
        if (this.chart) {
          this.chart.setOption(newOptions, true)
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption(this.options)
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped>
.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.chart-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chart-container {
  position: relative;
}
</style>